import { ref, computed } from 'vue'
import { bookBorrowAPI } from '@/api'
import { ElMessage } from 'element-plus'

// 图书借阅数据状态
export const bookBorrowData = ref([])
export const borrowers = ref([])
export const books = ref([])
export const borrowStatuses = ref([])
export const stats = ref({
  total_records: 0,
  total_borrowers: 0,
  total_books: 0,
  average_price: 0,
  today_records: 0,
  recent_data: []
})

// 加载状态
export const loading = ref(false)
export const statsLoading = ref(false)

// 分页状态
export const pagination = ref({
  page: 1,
  page_size: 20,
  total: 0,
  total_pages: 0
})

// 过滤条件
export const filters = ref({
  borrower: '',
  borrowed_book: '',
  borrow_status: '',
  start_date: '',
  end_date: ''
})

// 计算属性
export const hasData = computed(() => bookBorrowData.value.length > 0)
export const totalRecords = computed(() => pagination.value.total)

// 获取图书借阅数据列表
export async function fetchBookBorrowData(params = {}) {
  loading.value = true
  try {
    const queryParams = {
      page: pagination.value.page,
      page_size: pagination.value.page_size,
      ...filters.value,
      ...params
    }
    // 清除空值参数
    Object.keys(queryParams).forEach(key => {
      if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
        delete queryParams[key]
      }
    })
    const response = await bookBorrowAPI.getBookBorrowData(queryParams)
    bookBorrowData.value = response.data || []
    pagination.value = {
      page: response.page || 1,
      page_size: response.page_size || 20,
      total: response.total || 0,
      total_pages: response.total_pages || 0
    }
    return response
  } catch (error) {
    console.error('Fetch book borrow data error:', error)
    ElMessage.error('获取借阅数据失败')
    bookBorrowData.value = []
    return null
  } finally {
    loading.value = false
  }
}

// 添加图书借阅数据
export async function addBookBorrowData(data) {
  try {
    const response = await bookBorrowAPI.createBookBorrowData(data)
    ElMessage.success('借阅数据添加成功')
    // 刷新数据列表
    await fetchBookBorrowData()
    return response
  } catch (error) {
    console.error('Add book borrow data error:', error)
    const errorMessage = error.response?.data?.detail || '添加借阅数据失败'
    ElMessage.error(errorMessage)
    throw error
  }
}

// 删除图书借阅数据
export async function deleteBookBorrowData(id) {
  try {
    await bookBorrowAPI.deleteBookBorrowData(id)
    ElMessage.success('借阅数据删除成功')
    // 刷新数据列表
    await fetchBookBorrowData()
    return true
  } catch (error) {
    console.error('Delete book borrow data error:', error)
    const errorMessage = error.response?.data?.detail || '删除借阅数据失败'
    ElMessage.error(errorMessage)
    return false
  }
}

// 获取借阅者列表
export async function fetchBorrowers() {
  try {
    const response = await bookBorrowAPI.getBorrowers()
    borrowers.value = response || []
    return response
  } catch (error) {
    console.error('Fetch borrowers error:', error)
    ElMessage.error('获取借阅者列表失败')
    borrowers.value = []
    return []
  }
}

// 获取图书列表
export async function fetchBooks() {
  try {
    const response = await bookBorrowAPI.getBooks()
    books.value = response || []
    return response
  } catch (error) {
    console.error('Fetch books error:', error)
    ElMessage.error('获取图书列表失败')
    books.value = []
    return []
  }
}

// 获取借阅状态列表
export async function fetchBorrowStatuses() {
  try {
    const response = await bookBorrowAPI.getBorrowStatuses()
    borrowStatuses.value = response || []
    return response
  } catch (error) {
    console.error('Fetch borrow statuses error:', error)
    ElMessage.error('获取借阅状态失败')
    borrowStatuses.value = []
    return []
  }
}

// 获取统计信息
export async function fetchStats() {
  statsLoading.value = true
  try {
    const response = await bookBorrowAPI.getStats()
    stats.value = response || {
      total_records: 0,
      total_borrowers: 0,
      total_books: 0,
      average_price: 0,
      today_records: 0,
      recent_data: []
    }
    return response
  } catch (error) {
    console.error('Fetch stats error:', error)
    ElMessage.error('获取统计信息失败')
    stats.value = {
      total_records: 0,
      total_borrowers: 0,
      total_books: 0,
      average_price: 0,
      today_records: 0,
      recent_data: []
    }
    return null
  } finally {
    statsLoading.value = false
  }
}

// 设置过滤条件
export function setFilters(newFilters) {
  filters.value = { ...filters.value, ...newFilters }
  pagination.value.page = 1 // 重置页码
}

// 清除过滤条件
export function clearFilters() {
  filters.value = {
    borrower: '',
    borrowed_book: '',
    borrow_status: '',
    start_date: '',
    end_date: ''
  }
  pagination.value.page = 1
}

// 设置分页
export function setPagination(page, pageSize = null) {
  pagination.value.page = page
  if (pageSize) {
    pagination.value.page_size = pageSize
  }
}

// 获取最近的借阅数据
export function getRecentBookBorrowData(limit = 10) {
  return bookBorrowData.value.slice(0, limit)
}

// 按借阅者统计
export function getBookBorrowStatsByBorrower() {
  const borrowerStats = {}
  bookBorrowData.value.forEach(item => {
    if (!borrowerStats[item.borrower]) {
      borrowerStats[item.borrower] = 0
    }
    borrowerStats[item.borrower]++
  })
  return borrowerStats
}

// 按图书统计
export function getBookBorrowStatsByBook() {
  const bookStats = {}
  bookBorrowData.value.forEach(item => {
    if (!bookStats[item.borrowed_book]) {
      bookStats[item.borrowed_book] = 0
    }
    bookStats[item.borrowed_book]++
  })
  return bookStats
}

// 初始化数据
export async function initBookBorrowData() {
  await Promise.all([
    fetchBookBorrowData(),
    fetchBorrowers(),
    fetchBooks(),
    fetchBorrowStatuses(),
    fetchStats()
  ])
} 